package com.kaiwukj.android.ufamily.mvp.ui.page.mine.face;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.utils.CameraUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

@Route(path = ARouterUrlKt.ViseFaceActivityUrl)
public class ViseFaceActivity extends BaseActivity implements View.OnClickListener, SurfaceHolder.Callback {
    private Camera mCamera;
    private int mCameraId = 0;
    private LinearLayout surfaceview_lin;
    private SurfaceView surfaceView;
    private SurfaceHolder mHolder;
    //取消或重拍
    private TextView tv1;
    private ImageView img_camera;
    private ImageView img_face;
    //使用照片
    private TextView tv2;

    //需要保存的bitmap
    private Bitmap saveBitmap = null;
    //需要保存的图片地址
    private String img_path;
    //点击状态 1代表拍摄 2代表重拍
    private int state = 1;
    // private Tiny.FileCompressOptions compressOptions;

    @Override
    protected int getLayoutId() {
        //        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        return R.layout.activity_vise_face;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        mHolder = surfaceView.getHolder();
        mHolder.addCallback(this);
        surfaceview_lin = (LinearLayout) findViewById(R.id.surfaceview_lin);
        //取消或重拍
        tv1 = (TextView) findViewById(R.id.camera_tv1);
        tv1.setOnClickListener(this);
        img_camera = (ImageView) findViewById(R.id.img_camera);
        img_camera.setOnClickListener(this);
        img_face = (ImageView) findViewById(R.id.img_face);
        //使用照片
        tv2 = (TextView) findViewById(R.id.camera_tv2);
        tv2.setOnClickListener(this);

    }


    @Override
    protected void initData(Bundle savedInstanceState) {

      /*  compressOptions = new Tiny.FileCompressOptions();
        compressOptions.config = Bitmap.Config.RGB_565;
        compressOptions.quality = 50;


        DialogTakeFace dialogTakeFace = new DialogTakeFace(this);
        dialogTakeFace.showDialog();*/

        DisplayMetrics dm = this.getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;
        screenHeight = dm.heightPixels;
        switchCamera();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.camera_tv1:
                if (state == 1) {

                    finish();
                } else if (state == 2) {
                    if (!saveBitmap.isRecycled()) {
                        saveBitmap.recycle();
                    }
                    state = 1;
                    img_camera.setVisibility(View.VISIBLE);
                    img_camera.setEnabled(true);
                    tv2.setVisibility(View.GONE);
                    tv1.setText("取消");
                    img_face.setVisibility(View.GONE);
                    mCamera.startPreview();
                }
                break;

            case R.id.img_camera:
                takePhoto();
                img_camera.setEnabled(false);
                break;
            case R.id.camera_tv2:
                // DialogProgress.showDialog(UpdateFaceCameraActivity.this);
                showLoading("");
                // 使用照片时，先通过 sdk 判断图片中 人脸数量
                Intent data = new Intent();
                data.putExtra("face", img_path);
                setResult(RESULT_OK, data);
                finish();
                break;
            default:
                break;
        }
    }


    private void takePhoto() {
        mCamera.takePicture(null, null, new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {

                camera.stopPreview();

                isview = false;
                //将data 转换为位图 或者你也可以直接保存为文件使用 FileOutputStream
                //这里我相信大部分都有其他用处把 比如加个水印 后续再讲解
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                saveBitmap = null;
                saveBitmap = CameraUtil.getInstance().setTakePicktrueOrientation(mCameraId, bitmap);
//                saveBitmap = Bitmap.createScaledBitmap(saveBitmap, screenWidth, screenHeight, true);
//                saveBitmap = Bitmap.createBitmap(saveBitmap, 0, 0, screenWidth, screenHeight);
                img_face.setVisibility(View.VISIBLE);
                img_face.setImageBitmap(saveBitmap);

                img_path = getExternalFilesDir(Environment.DIRECTORY_DCIM).getPath() +
                        File.separator + System.currentTimeMillis() + ".jpeg";

                subscribe(Observable.create((ObservableOnSubscribe<File>) emitter -> {
                    //压缩图片 为保证 门禁机同步人脸效率与节省流量，对人脸图片进行压缩后再上传
                    byte[] bytes1 = ImageUtils.compressByQuality(saveBitmap, 100 * 1024L);
                    //byte[] bytes1 = ImageUtils.bitmap2Bytes(result, Bitmap.CompressFormat.JPEG);

                    File file = new File(img_path);
                    if (FileUtils.createOrExistsFile(file)) {
                        boolean isOk = FileIOUtils.writeFileFromBytesByStream(file, bytes1);
                        if (isOk) {
                            emitter.onNext(file);
                        } else {
                            emitter.onError(new Exception("file compress failed"));
                        }
                    } else {
                        emitter.onError(new FileNotFoundException("face file not found"));
                    }
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(file1 -> {
                            //获取图片完成
                            state = 2;
                            img_camera.setVisibility(View.INVISIBLE);
                            tv2.setVisibility(View.VISIBLE);
                            tv1.setText("重拍");
                        }, err -> {
                            showMessage("图片处理异常");
                            finish();
                        }));
               /* Tiny.getInstance().source(saveBitmap)
                        .asBitmap()
                        .withOptions(compressOptions)
                        .compress(new BitmapCallback() {
                            @Override
                            public void callback(boolean isSuccess, Bitmap bitmap, Throwable t) {
                                if (!isSuccess) {
                                    DialogProgress.dismissDialog();
                                    showToast("获取图片失败");
                                    return;
                                }
                                BitmapUtils.saveJPGE_After(mContext, bitmap, img_path, 100);
                                //获取图片完成
                                state = 2;
                                img_camera.setVisibility(View.INVISIBLE);
                                tv2.setVisibility(View.VISIBLE);
                                tv1.setText("重拍");
                            }

                        });*/


//                if (!bitmap.isRecycled()) {
//                    bitmap.recycle();
//                }
//                if (!saveBitmap.isRecycled()) {
//                    saveBitmap.recycle();
//                }

                //               finish();

            }
        });

    }

    public void switchCamera() {
        releaseCamera();
        mCameraId = (mCameraId + 1) % mCamera.getNumberOfCameras();
        mCamera = getCamera(mCameraId);
        if (mHolder != null) {
            startPreview(mCamera, mHolder);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mCamera == null) {
            mCamera = getCamera(mCameraId);
            if (mHolder != null) {
                startPreview(mCamera, mHolder);
            }
        }
    }

    /**
     * 获取Camera实例
     *
     * @return
     */
    private Camera getCamera(int id) {
        Camera camera = null;
        try {
            camera = Camera.open(id);
        } catch (Exception e) {

        }
        return camera;
    }


    /**
     * 预览相机
     */
    private void startPreview(Camera camera, SurfaceHolder holder) {
        try {
            setupCamera(camera);
            camera.setPreviewDisplay(holder);
            //亲测的一个方法 基本覆盖所有手机 将预览矫正
            CameraUtil.getInstance().setCameraDisplayOrientation(this, mCameraId, camera);
//            camera.setDisplayOrientation(90);
            camera.startPreview();
            isview = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean isview = false;

    /**
     * 设置
     */
    private void setupCamera(Camera camera) {
        Camera.Parameters parameters = camera.getParameters();
        if (parameters.getSupportedFocusModes().contains(
                Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        }
        float camera_w = parameters.getPreviewSize().width;
        float camera_h = parameters.getPreviewSize().height;
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) surfaceview_lin.getLayoutParams();
        params.height = (int) (screenWidth / camera_h * camera_w);
        surfaceview_lin.setLayoutParams(params);

        //这里第三个参数为最小尺寸 getPropPreviewSize方法会对从最小尺寸开始升序排列 取出所有支持尺寸的最小尺寸
        Camera.Size previewSize = CameraUtil.getInstance().getPropSizeForHeight(parameters.getSupportedPreviewSizes(), 1000);
        parameters.setPreviewSize(previewSize.width, previewSize.height);
        camera.setParameters(parameters);

        Camera.Size pictrueSize = CameraUtil.getInstance().getPropSizeForHeight(parameters.getSupportedPictureSizes(), 1000);
        parameters.setPictureSize(pictrueSize.width, pictrueSize.height);
        camera.setParameters(parameters);


    }

    private int picHeight;
    //屏幕宽高
    private int screenWidth;
    private int screenHeight;


    /**
     * 释放相机资源
     */
    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseCamera();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        startPreview(mCamera, holder);

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mCamera.stopPreview();
        startPreview(mCamera, holder);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        releaseCamera();

    }

}
